package io.github.junxworks.qt.modules.tushare.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;

import io.github.junxworks.junx.core.util.StringUtils;
import io.github.junxworks.qt.modules.data.service.DataStoreService;
import io.github.junxworks.qt.modules.tushare.Fields;
import io.github.junxworks.qt.modules.tushare.TushareAPIs;
import io.github.junxworks.qt.modules.tushare.entity.DStockIndexBasic;
import io.github.junxworks.qt.modules.tushare.entity.DStockIndexWeekly;
import io.github.junxworks.qt.modules.tushare.mapper.IndexMapper;
import io.github.junxworks.qt.modules.tushare.service.TradeInfoService;
import io.github.junxworks.qt.modules.tushare.service.TushareService;

@Service("TushareIndexService")
public class TushareIndexService extends TushareService {
	@Autowired
	private IndexMapper indexMapper;

	@Autowired
	private DataStoreService dataStoreService;

	@Autowired
	private TradeInfoService tradeInfoService;

	/**
	 * 更新指数基础数据.
	 * market:
	 * MSCI	MSCI指数
	 * CSI	中证指数
	 * SSE	上交所指数
	 * SZSE 深交所指数
	 * CICC 中金指数
	 * SW	申万指数
	 * OTH	其他指数
	 */
	public void fetchIndexProfiles(String codes) {
		if (StringUtils.isNull(codes)) {
			_fetchIndexProfile("SW");
		} else {
			String[] cs = codes.split(",");
			for (String s : cs) {
				_fetchIndexProfile(s.toUpperCase());
			}
		}
	}

	/**
	 * Save profile.
	 *
	 * @param status the status
	 */
	private void _fetchIndexProfile(String market) {
		Map<String, String> params = Maps.newHashMap();
		params.put("market", market);
		consumeTushareData(TushareAPIs.INDEX_BASIC, Fields.INDEX_BASIC_FIELDS, DStockIndexBasic.class, params, l -> {
			if (!l.isEmpty()) {
				indexMapper.deleteIndexDataByMarket(market);
				dataStoreService.insertBatch(l);
			}
		});
	}

	public void collectIndexWeeklyByDate(String date) {
		handleDataByDate(date, (d) -> consumeIndexDataWeeklyByDate(d));
	}

	public void collectIndexWeeklyByDateRange(String range) {
		handleDataWeekByWeek(range, (d) -> consumeIndexDataWeeklyByDate(d));
	}

	private void consumeIndexDataWeeklyByDate(String tradeDate) {
		String td = tradeInfoService.queryRecentTradeDate(tradeDate);
		Map<String, String> params = Maps.newHashMap();
		params.put("trade_date", td);
		consumeTushareData(TushareAPIs.INDEX_WEEKLY, Fields.INDEX_WEEKLY_FIELDS, DStockIndexWeekly.class, params, l -> {
			if (!l.isEmpty()) {
				indexMapper.deleteIndexWeeklyByTradeDate(td);
				dataStoreService.insertBatch(l);
			}
		});
	}

}
